﻿using System;
using System.ComponentModel;

namespace Kyoh.Lib.Component
{
    /// <summary><see cref="PropertyIndexAttribute"/> の与えられているプロパティを比較する <see cref="System.Collections.IComparer"/> の実装です。</summary>
    public class PropertyDescriptorComparer : System.Collections.IComparer
    {
        /// <summary><see cref="PropertyDescriptorComparer"/> の比較を行います。</summary>
        /// <param name="x"><see cref="PropertyDescriptorComparer"/> オブジェクト。</param>
        /// <param name="y"><see cref="PropertyDescriptorComparer"/> オブジェクト。</param>
        /// <returns>比較結果の <see cref="Int32"/></returns>
        public int Compare(object x, object y)
        {
            var cx = x as PropertyDescriptor;
            var cy = y as PropertyDescriptor;
            int ix = int.MaxValue,
                iy = int.MaxValue;

            if (cx == null && cy == null)
                return 0;
            else if (cx == null)
                return 1;
            else if (cy == null)
                return -1;

            foreach (var attr in cx.Attributes)
                if (attr is PropertyIndexAttribute)
                    ix = ((PropertyIndexAttribute)attr).Index;
            foreach (var attr in cy.Attributes)
                if (attr is PropertyIndexAttribute)
                    iy = ((PropertyIndexAttribute)attr).Index;

            if (ix == iy)
                return 0;
            else if (ix > iy)
                return 1;
            else
                return -1;
        }
    }
}
